package com.yuntsg.nnsfcp.service.front.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.front.entity.SendCodeLog;
import com.yuntsg.nnsfcp.front.mapper.SendCodeLogMapper;
import com.yuntsg.nnsfcp.service.front.ut.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ：ljx
 * @date ：Created in 2019/10/28
 */
@Service
public class SendCodeLogServiceImpl {

    @Resource
    private SendCodeLogMapper sendCodeLogMapper;

    @Resource
    private HttpServletRequest request;


    /**
     * 检查用户当日发送短信次数
     *
     * @param phone 手机号, 没有传null
     * @return true 可以发, false 不可以发
     */

    public boolean checkSendCode(String phone, Integer type) {

        Integer sendMaxNum = 0;
        SendCodeLog tempEntity = null;

        List<SendCodeLog> sendList
                = sendCodeLogMapper.selectList(new QueryWrapper<SendCodeLog>()
                .eq("phone", phone)
                .eq("send_time", getDate()));

        if (sendList != null && sendList.size() > 0) {
            for (SendCodeLog sendCodeLog : sendList) {
                sendMaxNum += sendCodeLog.getSendNum();

                if (tempEntity == null) {
                    if (sendCodeLog.getType().equals(type)) {
                        tempEntity = sendCodeLog;
                    }
                }
            }
            //5 == 当日可发送5次
            if (sendMaxNum >= 5) {
                return false;
            }

            //次数没有达到限制, 但是没有相同的类型, 仍可以继续发送
            if (tempEntity == null) {
                //添加
                save(phone, type);
            } else {
                //相同类型 次数递增
                Integer sendNum = tempEntity.getSendNum();
                tempEntity.setSendNum(sendNum + 1);
                sendCodeLogMapper.updateById(tempEntity);
            }
        } else {
            //添加
            save(phone, type);
        }

        return true;
    }

    private void save(String phone, Integer type) {
        SendCodeLog entity = getEntity();
        entity.setIp(IpUtil.getIp(request));
        entity.setPhone(phone);
        entity.setSendTime(getDate());
        entity.setType(type);
        entity.setSendNum(1);
        sendCodeLogMapper.insert(entity);
    }

    /**
     * 生成当前时间格式的字符串,作为文件名
     *
     * @return
     */
    private String getDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(new Date());
    }

    /**
     * 获取一个实体, 并且赋值默认值
     *
     * @return
     */
    private SendCodeLog getEntity() {
        SendCodeLog sendCodeLog = new SendCodeLog();
        sendCodeLog.setIp("");
        sendCodeLog.setPhone("");
        sendCodeLog.setType(0);
        sendCodeLog.setSendTime("");
        sendCodeLog.setSendNum(0);
        return sendCodeLog;
    }
}
